<?php
// +----------------------------------------------------------------------
// | 在线考试问答
// +----------------------------------------------------------------------
namespace app\webapp\controller;
use app\plus_exam\model\School as SchoolModel;
use app\plus_exam\model\History as HistoryModel;
use app\plus_exam\model\Question as QuestionModel;
use app\plus_exam\model\Category as CategoryModel;
use app\plus_exam\model\HistoryQuestion as HistoryQuestionModel;
use Request;

class Plusexam extends Base {

    const   OPTION_SINGLE   = 1;
    const   OPTION_MULTI    = 2;
    const   OPTION_JUDGE    = 3;

    const  EXAM_START    = 0;  //是否开启超时禁止进入考场 0 或 1
    const  EXAM_SUBMIT   = 0;  //是否开启超时禁止提交,开启影响倒计时提交 0 或 1
    const  EXAM_ONE      = 1;  //是否开启未答1题禁止提交 0 或 1
    const  EXAM_LOCKTIME = 1;  //是否开启限制多久禁止提交 0 或 1  

    private $school         = null;
    private $question       = null;
    private $history        = null;
    private $historyquestion= null;
    private $examcategory   = null;
    private $judge_option  = ['A' => '正确','B' => '错误'];

    public $exam_number     = 0;      //生成的题目的数量
    public $id              = 0;

    public $option_name     = [];
    public $category_list   = [];
    public $question_list   = [];

    private $option_key = ['A','B','C','D','E','F','G',];

    public function _initialize() {
        parent::_initialize();
        $this->HistoryModel    = new HistoryModel;
        $this->SchoolModel     = new SchoolModel;
        $this->QuestionModel   = new QuestionModel;
        $this->CategoryModel   = new CategoryModel;
        $this->HistoryQuestion = new HistoryQuestionModel;

        $this->assign('www_url',Request::domain());
        $this->assign('title','防震减灾知识网络竞赛');

        $this->option_name = [self::OPTION_SINGLE => '单选题',self::OPTION_MULTI  => '多选题',self::OPTION_JUDGE  => '判断题'];
        $category_list_raw = $this->CategoryModel->select_lists();
        foreach($category_list_raw as $key => $val) {
            $this->category_list[intval($val['id'])]['id'] = $val['id'];
            $this->category_list[intval($val['id'])]['name'] = $val['name'];
        }
    }

    /**
     * [lists 考试列表]
     * @return [type] [description]
     */
    public function index() {
        return $this->fetch('plus/exam/index');
    }
    /**
     * [lists_api 考试列表接口]
     * @return [json] [description]
     */
    public function lists_api() {
        $result = $this->SchoolModel->select_lists();
        if(count($result)){
            $data = [];
            foreach ($result as $key => $value) {
                $data[$key]['id']              = $value['id'];
                $data[$key]['name']            = $value['name'];
                $data[$key]['lock_time']       = $value['lock_time']/60;
                $data[$key]['is_repeat']       = $value['is_repeat'];
                $data[$key]['question_number'] = $value['question_number'];
                $data[$key]['one_point']       = $value['one_point'];
                $data[$key]['start_time']      = date('Y-m-d H:i:s',$value['start_time']);
                $data[$key]['end_time']        = date('Y-m-d H:i:s',$value['end_time']);
            }
            return json(['data'=>$data,'code'=>0,'message'=>'成功']);
        }else{
            return json(['code'=>1,'message'=>'没有内容']);
        }
    }

    /**
     * 开始答题
     * @return [type] [description]
     */
    public function start() {
        $id = input('id/d');
        $info = $this->SchoolModel->find_info($id);
        $this->assign('info',$info);
        if($id == 1){
            return $this->fetch('plus/exam/start_test');
        }else{
            return $this->fetch('plus/exam/start');
        }
        
    }

    /**
     * 开始答题
     * @return [type] [description]
     */
    public function start_api() {
        if(!$this->isLogin()) {
          return json(['code'=>403,'message'=>'你还没有登录']);
        }
        $id = input('id/d');
        if(!$id) {
            return json(['code'=>1,'message'=>'访问路径错误']);
        }
        $user = $this->getLoginUser();
        //判断练习次数
        if($id != 1){
            $is_number = $this->HistoryModel->where(['school_id'=>1,'status'=>1,'user_id'=>$user["id"]])->count();
            if($is_number < 3){
                return json(['code'=>1,'message'=>'你还没练习够60道题']);
            }
        }
        $result = $this->SchoolModel->find_info($id);
        if (!$result) {
            return json(['code'=>1,'message'=>'题库不存在']);
        }
        if(time() <= $result['start_time']) {
            return json(['code'=>1,'message'=>'还没有开始考试']);
        }
        if(time() >= $result['end_time']){
            return json(['code'=>1,'message'=>'考试时间已过']);
        } 
        //判断是否考试过
        $is_history = $this->HistoryModel->get_exam_history_by_user_id_lists(['school_id'=>$result['id'],'user_id'=>$user["id"],'status'=>1]);
        $is_repeat = count($is_history);
        if($is_repeat >= $result['is_repeat']){
            return json(['code'=>1,'message'=>'您已超过考试次数或考试时间未到所以禁止考试']);
        }

        //读取题库
        $result_history = $this->HistoryModel->get_exam_history_by_user_id(['school_id'=>$result['id'],'user_id'=>$user["id"],'status'=>0]);
        //判断是否进入过
        if (count($result_history) <= 0) {
            //获取随机题库
            $this->question_list = $this->QuestionModel->select_lists_api($result['category_id'],$result['question_number']);
            //把题库写入分数表（plus_exam_history）设置未考试状态 status =  0;
            //获取题库ID
            $question_id_list = [];
            foreach ($this->question_list as $val) {
                $question_id_list[] = intval($val['id']);
            }
            $data['user_id']       = $user["id"];
            $data['school_id']     = $result['id'];
            $data['question_list'] = json_encode($question_id_list);
            $data['status']        = 0;
            $data['create_time']   = time();
            $data['update_time']   = time();
            $history_id = $this->HistoryModel->add_data($data);
            //更新答案
            $history_question = [
                'history_id'    => $history_id,
                'school_id'     => $data['school_id'],
                'question_list' => json_encode($this->question_list)
            ];
            $this->HistoryQuestion->add_data($history_question);
            //获取考试开始时间
            $start_time = time(); 
        } else {
            $History_result= $this->HistoryQuestion->find_info(['history_id' => $result_history['id']]);
            $this->question_list = json_decode($History_result['question_list'],true);
            //获取考试开始时间
            $start_time = strtotime($result_history['create_time']);  
        }
        //关闭超时禁止进入考场
        $now_time  = time() - $start_time;
        $lock_time = $result['lock_time'] - $now_time;
        if(self::EXAM_START){
            if($this->lock_time <= 0){
                return json(['code'=>1,'message'=>'已超时禁止再进入']);
            }
        }
        //考试题库
        $question_lists = $this->make_question_readable();
        if(count($question_lists)){
            return json(['code'=>0,'data'=>$question_lists,'message'=>'成功']);
        }else{
            return json(['code'=>1,'message'=>'没有题目内容']);
        }
    }

    /**
     * [Submit 提交考试]
     */
    public function submit(){
        if(!$this->isLogin()) {
          return json(['code'=>403,'message'=>'你还没有登录']);
        }
        $user = $this->getLoginUser();
        $data = [
            'user_id'   => $user["id"],
            'school_id' => input('post.school_id/d'),
            'answer'    => input('post.answer/a')
        ];
        $validate = $this->validate($data,'Plusexam.add');
        if(true !== $validate){
            return json(['code'=>1,'message'=>$validate]);
        }
        if(!$data['school_id']){
            return json(['code'=>1,'message'=>'访问路径错误']);
        }
        $result = $this->SchoolModel->find_info($data['school_id']);
        if (!$result){
            return json(['code'=>1,'message'=>'题库不存在']);
        } 
        if(time() <= $result['start_time']) {
            return json(['code'=>1,'message'=>'本场还没有开始']);
        }
        if(time() >= $result['end_time']) {
            return json(['code'=>1,'message'=>'提交时间已过']);
        }
        //判断交卷时间是否超过
        $result_history = $this->HistoryModel->get_exam_history_by_user_id(['school_id'=>$result['id'],'user_id'=>$user["id"],'status'=>0]);
        if($result_history){
            if(self::EXAM_LOCKTIME){
                //限制多久禁止提交
                $start_lock_time          = strtotime($result_history['create_time']) + $result['start_lock_time'];
                $start_lock_time_now_time = $result['start_lock_time'] / 60;
                if($start_lock_time <= strtotime($result_history['create_time'])){
                    return json(['code'=>1,'message'=>'对不起!'.$start_lock_time_now_time.'分钟内禁止提交']);
                }
            }
            if(self::EXAM_SUBMIT){
                //关闭超时禁止提交
                $now_time  = time() - strtotime($result_history['create_time']);
                $lock_time = $result['lock_time'] - $now_time;
                if($lock_time <=0){
                    return json(['code'=>1,'message'=>'你已超时禁止再提交']);
                }
            }
        }else{
            return json(['code'=>1,'message'=>'不存在或禁止提交']);
        }
        $is_repeat = intval($result['is_repeat']);
        if(!$is_repeat){
            return json(['code'=>1,'message'=>'允许参加 0 次,请联系您的老师']);
        }
        //查询是否考过
        $is_history = $this->HistoryModel->get_exam_history_by_user_id_lists(['school_id'=>$result['id'],'user_id'=>$user["id"],'status'=>1]);
        $is_history_count = count($is_history);
        if($is_repeat <= $is_history_count){
            return json(['code'=>0,'message'=>'您只允许提交'.$is_repeat.'次']);
        }
        //判断是多选还是单选
        if(is_array($data['answer'])){
            foreach ($data['answer'] as $key => $value) {
                if(is_array($value)){
                    $answer[$key] = implode('',$value);
                }else{
                    $answer[$key] = $value;
                }
            }
            $answer_list = json_encode($answer);
        }else{
            if(self::EXAM_ONE){
                return json(['code'=>0,'message'=>'您一道题都没做呀!'.$is_repeat.'次']);
            }else{
                $answer[0] = [];
            }
            $answer_list = json_encode($answer);
        }
        $score = $this->QuestionModel->get_score($answer,intval($result['one_point']));  //统计分数
        $history_data = [
            "score"       => $score,
            "status"      => 1,
            "answer_list" => $answer_list,
            "update_time" => time(),
        ];
        $history_where = [
            "user_id"   => $user["id"],
            "school_id" => $result['id'],
            "status"    => 0,
        ];
        $rel = $this->HistoryModel->submit_add($history_where,$history_data);
        if($rel){
            return json(['code'=>0,'message'=>'提交成功,返回查看分数']);
        }else{
            return json(['code'=>1,'message'=>'提交失败']);
        }
    }
    
    /**
     * 我的成绩
     * @return [type] [description]
     */
    public function history() {
        return $this->fetch('plus/exam/history');
    }

    /**
     * 我的成绩API
     * @return [type] [description]
     */
    public function history_api() {
        if(!$this->isLogin()) {
          return json(['code'=>403,'message'=>'你还没有登录']);
        }
        $user = $this->getLoginUser();
        $result = $this->HistoryModel->get_exam_user_history($user["id"]);
        if(empty(count($result))){
            return json(['code'=>1,'message'=>'暂无成绩']);
        }else{
            return json(['code'=>0,'data'=>$result,'message'=>'成功']);
        }
    }

    /**
     * [make_question_readable 遍历题库列表]
     * @return [array] [新的题库列表]
     */
    private function make_question_readable() {
        foreach($this->question_list as $key => $val) {
            $question_list[$key] = $this->make_single_question_readable($val);
        }
        return $question_list;
    }

    /**
     * [make_single_question_readable 转换题库类型和名称]
     * @param  [array] $question [题库列表]
     * @return [array]           [新的题库列表]
     */
    private function make_single_question_readable($question) {
        $question['type_name'] = $this->option_name[intval($question['type'])];
        $question['category']  = $this->category_list[intval($question['category_id'])]['name'];
        $question_ary = json_decode($question['options'],true);
        $i=0;
        foreach($question_ary as $key => $val) {
            $i++;
            $data[] = ['value'=>$key,'name' =>$val];
        }
        $question['option_list'] = $data;
        return $question;
    }
}
